<?php

namespace App\Admin\Http\Controllers\Auth;

use Hash;
use Lang;
use Illuminate\Http\Request;
use App\Admin\Eloquent\User;
use App\Admin\Http\Controllers\Controller;

class AuthController extends Controller
{
    /**
     * 创建一个用户认证控制器实例
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('admin.guest', ['except' => 'getLogout']);
    }

    /**
     * 登录表单
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogin()
    {
        return view('admin.auth.login');
    }

    /**
     * 登录请求
     *
     * @param  Request $request
     * @return \Illuminate\Http\Response
     */
    public function postLogin(Request $request)
    {
        $this->validateLogin($request);

        $credentials = $request->only('username', 'password');

        $user = User::retrieveByCredentials($credentials);

        if (!is_null($user) && $this->validateCredentials($user, $credentials)) {
            #$request->session()->set($this->getLoginUserSessionKey(), $user);
            session([$this->getLoginUserSessionKey() => $user]);
            return redirect()->intended(admin_action('HomeController@index'));
        }

        return back()
            ->withInput($request->only('username', 'remember'))
            ->withErrors([
                'username' => $this->getLoginFailedMessage()
            ]);
    }

    /**
     * 注销登陆用户
     *
     * @param  Request $request
     * @return \Illuminate\Http\Response
     */
    public function getLogout(Request $request)
    {
        $request->session()->forget($this->getLoginUserSessionKey());

        return redirect()->intended(admin_action('Auth\AuthController@getLogin'));
    }

    /**
     * 验证登录请求
     *
     * @param  Request  $request
     * @return void
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            'username' => 'required', 
            'password' => 'required', 
        ]);
    }

    /**
     * 校验用户登录凭证
     *
     * @param  User  $user
     * @param  array  $credentials
     * @return bool
     */
    protected function validateCredentials(User $user, array $credentials)
    {
        $plain = md5($credentials['password']);

        return Hash::check($plain, $user->password);
    }

    /**
     * 登录失败提示信息
     *
     * @return string
     */
    protected function getLoginFailedMessage()
    {
        return Lang::has('auth.failed') ? Lang::get('auth.failed') : '用户名或密码错误。';
    }
}